package io.gitee.xjt2016.modules.api.extension;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.vdurmont.emoji.EmojiParser;
import jetbrick.template.JetAnnotations;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 公共函数
 * <p>
 * Created by biezhi on 2017/2/21.
 */
@JetAnnotations.Functions
public final class Commons {

    private static final String TEMPLATES = "/templates/";
    private static final Pattern SRC_PATTERN = Pattern.compile("src\\s*=\\s*\'?\"?(.*?)(\'|\"|>|\\s+)");

    public static String json(Object o) {
        return JSON.toJSONString(o);
    }

    /**
     * 判断字符串不为空
     */
    public static boolean not_blank(String str) {
        return StringUtils.isNotBlank(str);
    }

    public static boolean equals(String str, String str2) {
        return StringUtils.equals(str, str2);
    }


    public static boolean not_empty(Collection coll) {
        return CollectionUtils.isNotEmpty(coll);
    }

    /**
     * 截取字符串
     */
    public static String substr(String str, int len) {
        if (str.length() > len) {
            return str.substring(0, len);
        }
        return str;
    }

    public static Set<String> split(String str) {
        if (StringUtils.isNotBlank(str)) {
            return Arrays.stream(str.split("[,，]")).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        }
        return new HashSet<>();
    }

    /**
     * 格式化unix时间戳为日期
     */
    public static String fmtdate(Integer unixTime) {
        return fmtdate(unixTime, "yyyy-MM-dd");
    }

    /**
     * 格式化日期
     */
    public static String fmtdate(Date date, String fmt) {
        return DateUtil.format(date, fmt);
    }

    /**
     * 格式化unix时间戳为日期
     */
    public static String fmtdate(Integer unixTime, String patten) {
        if (null != unixTime && StringUtils.isNotBlank(patten)) {
            return DateUtil.format(new Date(unixTime), patten);
        }
        return "";
    }

    /**
     * 获取随机数
     */
    public static String random(int max, String str) {
        return RandomUtil.randomInt(1, max) + str;
    }

    /**
     * An :grinning:awesome :smiley:string &#128516;with a few :wink:emojis!
     * <p>
     * 这种格式的字符转换为emoji表情
     */
    public static String emoji(String value) {
        return EmojiParser.parseToUnicode(value);
    }

}
